<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <el-dialog v-model="props.dataVisible" :title="'查看数据详情'" width="1200px" append-to-body :before-close="closeDialog">
    <el-button style="margin-bottom: 10px;" size="small" type="primary" @click="exportExcel">导出Excel</el-button> 
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="xindex" label="x轴取值" width="150" align="center" />
      <el-table-column prop="groupName" label="位置" width="150" align="center" />
      <el-table-column label="MAX" align="center">
        <el-table-column prop="maxData" :label="dataName" width="120" align="center" />
        <el-table-column prop="maxDataLoadCase" label="工况" width="120" align="center" />
        <el-table-column prop="elementId" label="单元编号" width="120" align="center" />
        <el-table-column v-for="item in maxLabelValue" :key="item.value" :prop="item.value" :label="item.label" width="120" align="center" />
      </el-table-column>
      <el-table-column label="MIN" align="center">
        <el-table-column prop="minData" :label="dataName" width="120" align="center" />
        <el-table-column prop="minDataLoadCase" label="工况" width="120" align="center" />
        <el-table-column v-for="item in minLabelValue" :key="item.value" :prop="item.value" :label="item.label" width="120" align="center" />
      </el-table-column>
    </el-table>
    <template #footer>
      <div class="dialog-footer" style="text-align: center">
        <el-button size="small" @click="closeDialog">返回</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import * as XLSX from 'xlsx';
const props = defineProps(['dataVisible', 'rowData']);
const emit = defineEmits(['handleEvent']);
const tableData = ref([]);
const maxLabelValue = ref([]);
const minLabelValue = ref([]);
const dataName = ref('');
// const testData = [
//           { name: '张三', gender: '男', age: 28, email: 'zhangsan@example.com', phone: '13800138000' },
//           { name: '李四', gender: '女', age: 32, email: 'lisi@example.com', phone: '13900139000' },
//           { name: '王五', gender: '男', age: 25, email: 'wangwu@example.com', phone: '13700137000' },
//           { name: '赵六', gender: '女', age: 29, email: 'zhaoliu@example.com', phone: '13600136000' },
//           { name: '钱七', gender: '男', age: 35, email: 'qianqi@example.com', phone: '13500135000' }
//         ]
const closeDialog = () => {
  emit('handleEvent');
};

const getTableData = () => {
  const dataList = JSON.parse(JSON.stringify(props.rowData.dataList));
  const length = dataList.length - 1;
  let roundCounter = 0; // 初始化后缀计数器
  dataList.forEach((item) => {
    item.dataDetailList
      .sort((a, b) => a.xindex - b.xindex)
      .forEach((detail) => {
        if (detail.maxDataPercentDiff !== null) {
          detail.maxDataPercentDiff = (detail.maxDataPercentDiff * 100).toFixed(2) + '%';
        }
        if (detail.minDataPercentDiff !== null) {
          detail.minDataPercentDiff = (detail.minDataPercentDiff * 100).toFixed(2) + '%';
        }
      });
    item.dataDetailList = item.dataDetailList.map((params) => {
      return { ...params, type: item.name };
    });
    if (!item.isBaseRound) {
      roundCounter++;
      let roundSuffix = `${roundCounter}`; // 根据计数器决定后缀
      item.dataDetailList = item.dataDetailList.map((detailItem) => {
        let newDetailItem = {};
        for (let key in detailItem) {
          if (detailItem.hasOwnProperty(key)) {
            if (key === 'xindex') {
              newDetailItem[key] = detailItem[key]; // 不添加后缀
            } else {
              newDetailItem[`${key}_${roundSuffix}`] = detailItem[key]; // 添加后缀
            }
          }
        }
        return newDetailItem;
      });
    }
  });
  tableData.value = dataList.flatMap((data) =>
    data.dataDetailList.flatMap((detail) => {
      return { groupName: props.rowData.groupName, ...detail };
    })
  );
  let mergedData = {};
  tableData.value.forEach((item) => {
    let x = item.xindex;
    if (!mergedData[x]) {
      mergedData[x] = { ...item }; // 如果mergedData里还没有这个elementId，则创建一个新对象
    } else {
      mergedData[x] = { ...mergedData[x], ...item }; // 合并对象，新的键会加入，旧的键会被覆盖
    }
  });
  let result = Object.values(mergedData);
  tableData.value = result;
  dataName.value = tableData.value[0].type;
  for (let i = 1; i <= length; i++) {
    maxLabelValue.value.push(
      { label: tableData.value[0]['type_' + i], value: `maxData_${i}` },
      { label: '工况', value: `maxDataLoadCase_${i}` },
      { label: '单元编号', value: `elementId_${i}` },
      { label: '差异', value: `maxDataPercentDiff_${i}` }
    );
    minLabelValue.value.push(
      { label: tableData.value[0]['type_' + i], value: `minData_${i}` },
      { label: '工况', value: `minDataLoadCase_${i}` },
      { label: '单元编号', value: `elementId_${i}` },
      { label: '差异', value: `minDataPercentDiff_${i}` }
    );
  }
};

const exportExcel = () => {
  // 创建工作簿
  const wb = XLSX.utils.book_new();
  wb.SheetNames.push("数据详情");
  
  // 准备数据
  const data = [];
  
  // 第一行表头
  const headerRow1 = [
    'x轴取值', 
    '位置',
    'MAX', '', '', '', '', '', '',  // 合并七列
    'MIN', '', '', '', '', '',      // 合并六列
  ];
  
  // 第二行表头
  const commonLabels = maxLabelValue.value.map(item => item.label);
  let headerRow2 = [
    '', 
    '',
    dataName.value, '工况', '单元编号', commonLabels,
    dataName.value, '工况', commonLabels
  ];
  console.log('headerRow2', tableData.value)
  headerRow2 = headerRow2.flat();

  
  data.push(headerRow1);
  data.push(headerRow2);
  
  // 添加数据行
  tableData.value.forEach((item, index) => {
    data.push([
      item.xindex, // x轴取值
      item.groupName, // 位置
      item.maxData,
      item.maxDataLoadCase,
      item.elementId,
      item.maxData_1,
      item.maxDataLoadCase_1,
      item.elementId_1,
      item.maxDataPercentDiff_1,
      item.minData,
      item.minDataLoadCase,
      item.minData_1,
      item.minDataLoadCase_1,
      item.elementId_1,
      item.minDataPercentDiff_1
    ]);
  });
  
  // 创建工作表
  const ws = XLSX.utils.aoa_to_sheet(data, {cellStyles: true});
  
  // 设置合并区域
  ws['!merges'] = [
    { s: { r: 0, c: 0 }, e: { r: 1, c: 0 } },
    { s: { r: 0, c: 1 }, e: { r: 1, c: 1 } },
    // 基本信息合并 (B1:D1)
    { s: { r: 0, c: 2 }, e: { r: 0, c: 8 } },
    
    // 联系信息合并 (E1:F1)
    { s: { r: 0, c: 9 }, e: { r: 0, c: 14 } },
    
    // 操作合并 (G1:G2)
    // { s: { r: 0, c: 6 }, e: { r: 1, c: 6 } }
  ];
  
  // 设置列宽
  const colWidths = [
    { wch: 10 }, 
    { wch: 10 }, 
    { wch: 20 }, 
    { wch: 10 }, 
    { wch: 10 }, 
    { wch: 20 },
    { wch: 10 }, 
    { wch: 10 }, 
    { wch: 10 }, 
    { wch: 20 },
    { wch: 10 },
    { wch: 20 },
    { wch: 10 },
    { wch: 10 },
    { wch: 10 },
  ];
  ws['!cols'] = colWidths;
  
  // 添加工作表到工作簿
  wb.Sheets["数据详情"] = ws;
  
  // 生成Excel文件并下载
  const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
  
  function s2ab(s) {
    const buf = new ArrayBuffer(s.length);
    const view = new Uint8Array(buf);
    for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xFF;
    return buf;
  }
  
  const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });
  saveAs(blob, "数据详情.xlsx");
  
  showSuccessMessage();
}
const showSuccessMessage = () => {
  // alert('Excel文件导出成功！\n文件名: 员工信息表.xlsx');
}

onMounted(() => {
  getTableData();
});
</script>

<style lang="scss" scoped></style>
